package com.aijle.videopaper.util;

import android.app.Activity;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import androidx.core.app.NotificationManagerCompat;
import android.text.TextUtils;

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

public class PermissionCheck{
    /**
     * 检查应用是否有悬浮窗权限（Android 6.0以上需要检查悬浮窗权限）
     */
    public static boolean hasOverlayPermission(Context context) {
        if (Build.VERSION.SDK_INT >= 23) {
            return Settings.canDrawOverlays(context);
        }
        return true;
    }

    public static String getForegroundProcess(Context context) {
        String topPackageName = null;
        UsageStatsManager usage = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        long time = System.currentTimeMillis();
        List<UsageStats> stats = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*1000, time);
        if (stats != null) {
            SortedMap<Long, UsageStats> runningTask = new TreeMap<Long,UsageStats>();
            for (UsageStats usageStats : stats) {
                runningTask.put(usageStats.getLastTimeUsed(), usageStats);
            }
            if (runningTask.isEmpty()) {
                return null;
            }
            topPackageName =  runningTask.get(runningTask.lastKey()).getPackageName();
        }
//        if(topPackageName==null) {
//            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
//            context.startActivity(intent);
//        }

        return topPackageName;
    }
    /**
     * 检查应用通知权限
     *
     * @param context
     * @return
     */
    public static boolean hasNotifyPermission(Context context) {
        NotificationManagerCompat manager = NotificationManagerCompat.from(context);
        return manager.areNotificationsEnabled();
    }

    /**
     * 获取指定AccessibilityService的授权状态（服务是否已授权开启）
     *
     * @param context
     * @param serviceName 服务名称
     */
    public static boolean getServiceState(Context context, String serviceName) {
        int enable = 0;
        try {
            // 是否允许辅助服务运行（当前应用程序是否有辅助服务，有辅助服务返回1，没有辅助服务返回0）
            enable = Settings.Secure.getInt(context.getApplicationContext().getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
            return false;
        }
        if (enable == 1) {
            // 获取所有可使用的服务（会以String形式返回，多个服务用":"分割）
            String accessibilityString = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            // 创建字符串分割器（用":"分割字符串）
            TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(':');
            splitter.setString(accessibilityString);
            // 遍历服务名称（查是否含有名为serviceName辅助服务）
            while (splitter.hasNext()) {
                String accessibilityService = splitter.next();
                if (accessibilityService.equals(serviceName)) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    }

    public static boolean readAndWriteExternalStorage(Context context){
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    public static boolean audioRecord(Context context){
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.RECORD_AUDIO}, 2);
                return false;
            } else {
                return true;
            }
        }
        return true;

    }

    public static boolean readAndWriteContacts(Context context){
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS}, 3);
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    public static boolean vibrate(Context context){
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.VIBRATE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.VIBRATE}, 4);
                return false;
            } else {
                return true;
            }
        }
        return true;

    }

    public static boolean sendSms(Context context){
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.SEND_SMS}, 5);
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    //Just like this you can implement rest of the permissions.
}